package com.jfm.jfmc.plugin.icmp.collect;

import cn.hutool.core.util.StrUtil;
import com.jfm.jfmc.plugin.icmp.enums.ResultValue;
import com.jfm.jfmc.plugin.icmp.utils.ICMPUtil;
import com.jfm.jfmm.collector.driver.ACollectorDriver;
import com.jfm.jfmm.collector.driver.ICMPDriver;
import com.jfm.jfmm.collector.entity.collect.CheckResult;
import com.jfm.jfmm.collector.entity.collect.CollectResult;
import com.jfm.jfmm.collector.entity.collect.Param;
import com.jfm.jfmm.collector.entity.collect.param.ICMPParam;
import com.jfm.jfmm.collector.entity.collect.result.ICMPResult;
import com.jfm.jfmm.collector.enums.ResultType;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author DYang
 * @since 2024-10-11 22:25
 *
 * ICMP 采集器
 */
@Slf4j
@Service
public class ICMPCollect extends ICMPDriver {

    @PostConstruct
    @Override
    public void register() {
        ACollectorDriver.collectorMap.put(this.supportProtocol(), this);
    }
    @Override
    public CheckResult perCheck(Param reqParam) {

        ICMPParam param = this.transformParam(reqParam);

        if (param == null) return new CheckResult(ResultType.EMPTY_PARAM);

        if (StrUtil.isEmpty(param.getHost())) return new CheckResult(ResultType.EMPTY_PARAM,"icmp ip is required");

        return new CheckResult(ResultType.SUCCESS);
    }


    @Override
    public CollectResult collect(Param reqParam) {
        long startTime = System.currentTimeMillis();
        CollectResult collectResult = new CollectResult();

        ICMPParam param = this.transformParam(reqParam);
        try {
            long timeout = param.getTimeout() == null ? 5000 : param.getTimeout();
            boolean status = ICMPUtil.isValidHost(param.getHost(), timeout);
            long responseTime = System.currentTimeMillis() - startTime;

            ICMPResult result = ICMPResult.build()
                    .host(param.getHost())
                    .delay(responseTime)
                    .result(status ? ResultValue.SUCCESS.getValue() : ResultValue.FAIL.getValue());

            collectResult
                    .result(result)
                    .protocol(this.supportProtocol())
                    .startTime(startTime)
                    .responseTime(responseTime);

        } catch (Exception e) {
            log.error("icmp collect error", e);
            throw new RuntimeException(e);
        }
        return collectResult;
    }

}
